package cn.yuemouren.security.browser;

import cn.yuemouren.security.core.authentication.AbstractChannelSecurityConfig;
import cn.yuemouren.security.core.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import cn.yuemouren.security.core.authorize.AuthorizeConfigManager;
import cn.yuemouren.security.core.properties.SecurityConstants;
import cn.yuemouren.security.core.properties.SecurityProperties;
import cn.yuemouren.security.core.validate.code.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.social.security.SpringSocialConfigurer;

import javax.sql.DataSource;

/**
 * @Author: Timi
 * @Description: security 拦截配置
 * @Date: 2020/6/3 16:10
 */
@Configuration
@EnableWebSecurity
public class BrowserSecurityConfig extends AbstractChannelSecurityConfig {

    //配置文件获取登录页
    @Autowired
    private SecurityProperties securityProperties;
    //注入数据源
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;
    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;
    @Autowired
    private SpringSocialConfigurer timiSocialConfigurer;
    @Autowired
    private SessionInformationExpiredStrategy sessionInformationExpiredStrategy;
    @Autowired
    private InvalidSessionStrategy invalidSessionStrategy;
    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;
    @Autowired
    private AuthorizeConfigManager authorizeConfigManager;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        applyPasswordAuthenticationConfig(http);

        http.apply(validateCodeSecurityConfig)
                .and()
                    .apply(smsCodeAuthenticationSecurityConfig)
                .and()
                    .apply(timiSocialConfigurer)
                .and()
                    //session管理
                    .sessionManagement()
                        //session无效策略
                        .invalidSessionStrategy(invalidSessionStrategy)
                        //最大session连接数
                        .maximumSessions(securityProperties.getBrowser().getSession().getMaximumSessions())
                        //session连接数达到最大时不允许登录
                        .maxSessionsPreventsLogin(securityProperties.getBrowser().getSession().isMaxSessionsPreventsLogin())
                        //session过期策略
                        .expiredSessionStrategy(sessionInformationExpiredStrategy)
                .and()
                .and()
                .logout()
                    .logoutUrl("/signUp")
                    .logoutSuccessHandler(logoutSuccessHandler)
                    //根据cookie名字删除cookie
                    //.deleteCookies()
                .and()
                //开启security记住我
                .rememberMe()
                    //指定获取token的数据库操作类
                    .tokenRepository(persistentTokenRepository())
                    //过期时间
                    .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds())
                    //使用哪个details处理逻辑
                    .userDetailsService(userDetailsService)
                .and()
                //关闭csrf认证
                .csrf().disable();
        authorizeConfigManager.config(http.authorizeRequests());
    }

    /**
     * 获取数据库操作对象，用于获取token值
     * 首次使用请执行建表语句  create table persistent_logins (username varchar(64) not null, series varchar(64) primary key,token varchar(64) not null, last_used timestamp not null)
     */
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepositoryImpl = new JdbcTokenRepositoryImpl();
        jdbcTokenRepositoryImpl.setDataSource(dataSource);
        return jdbcTokenRepositoryImpl;
    }
}
